package service

import (
	"day12_16_shop/config"
	"day12_16_shop/internal/api/request"
	"day12_16_shop/internal/models/dao"
	"day12_16_shop/pkg"
	"gorm.io/gorm"
	"strconv"
)

func CreateShop(shop *request.ShopCreateRequest, id int) (int, string) {
	much := pkg.HowMuch(shop)
	shops := dao.Shop{
		UserId:    id,
		Phone:     shop.Phone,
		HowBig:    shop.HowBig,
		WhereBuy:  shop.WhereBuy,
		GoodOrBad: shop.GoodOrBad,
		Price:     much,
	}
	err := config.DB.Model(&dao.Shop{}).Create(&shops).Error
	if err != nil {
		return 0, "商品发布失败"
	}
	return int(shops.ID), ""
}

func ListShop(shop *request.ShopListRequest) ([]*dao.Shop, string) {
	query := config.DB.Model(&dao.Shop{})
	var shops []*dao.Shop
	if shop.Phone != "" && shop.GoodOrBad != 0 && shop.HowBig != 0 {
		err := query.Where("phone=? and good_or_bad=? and how_big=? and status=1", shop.Phone, shop.GoodOrBad, shop.HowBig).
			Scopes(Paginate(shop.Page, shop.PageSize)).Find(&shops).Error
		if err != nil {
			return nil, "展示失败"
		}
		return shops, ""

	} else if shop.Phone != "" || shop.GoodOrBad != 0 || shop.HowBig != 0 {
		if shop.Phone != "" {
			query = query.Where("phone=? and status=1", shop.Phone)
		}
		if shop.GoodOrBad != 0 {
			query = query.Where("good_or_bad=? and status=1", shop.GoodOrBad)
		}
		if shop.HowBig != 0 {
			query = query.Where("how_big=? and status=1", shop.HowBig)
		}
		query.Scopes(Paginate(shop.Page, shop.PageSize)).Find(&shops)
		return shops, ""
	}
	err := query.Where("status=1").Find(&shops).Error
	if err != nil {
		return nil, "展示失败"
	}
	return shops, ""
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		page, _ = strconv.Atoi(strconv.Itoa(page))
		if page <= 0 {
			page = 1
		}

		pageSize, _ = strconv.Atoi(strconv.Itoa(pageSize))
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func Buy(shopId int, userId int) (int, string) {
	var shop *dao.Shop
	err := config.DB.Model(&dao.Shop{}).Where("id=?", shopId).Limit(1).Find(&shop).Error
	if err != nil {
		return 0, "购买失败"
	}
	if shop.ID == 0 {
		return 0, "购买失败"
	}
	if shop.UserId == userId {
		return 0, "您自己不能购买自己的商品"
	}
	shops := dao.ShopBuy{
		UserId: userId,
		ShopId: shopId,
	}
	err = config.DB.Model(&dao.ShopBuy{}).Create(&shops).Error
	if err != nil {
		return 0, "购买失败"
	}
	config.DB.Model(&dao.Shop{}).Where("id=?", shopId).Update("status", 2)
	return int(shops.ID), ""
}
